package com.itdfq.springbootmongodb.domain;

import org.bson.Document;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperationContext;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author: QianMo
 * @date: 2021/12/24 10:38
 * @mark:
 */
public class GeoNear2Document implements AggregationOperation {

    private Document nearQuery;
    @Override
    public Document toDocument(AggregationOperationContext context) {
        return null;
    }

    public GeoNear2Document(Query query, Point point, double maxDistance) {
        this.nearQuery = new Document("near", new Document("type", "Point")
                .append("coordinates", new double[]{point.getX(), point.getY()}))
                .append("distanceField", "dist")
                .append("query", query.getQueryObject())
                .append("maxDistance", maxDistance)
                .append("spherical", true);
    }

    @Override
    public List<Document> toPipelineStages(AggregationOperationContext context) {
        Document command = context.getMappedObject(nearQuery);
        return Collections.singletonList(new Document("$geoNear", command));

    }

    @Override
    public String getOperator() {
        return AggregationOperation.super.getOperator();
    }
}
